<script setup lang="ts">
import { ref, onMounted, watch, defineAsyncComponent } from "vue";
import { useMerchantStore } from "@/store";
import { listFoods, createFood, updateFood, deleteFood } from "@/api";
import { ElMessage, ElMessageBox } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";

// 导入ProductForm组件
const ProductForm = defineAsyncComponent(
  () => import("@/components/merchant/ProductForm.vue")
);

const merchantStore = useMerchantStore();
const products = ref<any[]>([]);
const loading = ref(false);
const formLoading = ref(false);
const categories = ref<any[]>([]);

const productDialogVisible = ref(false);
const isEdit = ref(false);
const productForm = ref<any>({
  name: "",
  categoryId: "",
  price: 0,
  originalPrice: 0,
  inventory: 0,
  description: "",
  image: "",
  status: 1,
});

// 添加分页相关的状态
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 添加商品状态过滤
const statusFilter = ref<string>("");

// 商品状态映射
const statusMap = {
  ON_SHELF: { text: "已上架", type: "success" },
  OFF_SHELF: { text: "已下架", type: "info" },
  PENDING: { text: "待审核", type: "warning" },
  SUSPENDED: { text: "已禁用", type: "danger" },
};

// 获取状态显示信息
const getStatusInfo = (status: string) => {
  return statusMap[status] || { text: "未知状态", type: "info" };
};

const fetchProducts = async (
  page = 1,
  size = 10,
  status = statusFilter.value
) => {
  if (!merchantStore.currentStoreId) {
    products.value = [];
    console.log("未选择店铺，无法获取商品列表");
    return;
  }

  loading.value = true;
  console.log("======================================");
  console.log(
    `开始获取商品列表，店铺ID: ${
      merchantStore.currentStoreId
    }, 页码: ${page}, 每页数量: ${size}, 状态过滤: ${status || "全部"}`
  );
  console.log("======================================");

  try {
    // 添加分页和状态过滤参数
    const params: any = {
      page: page - 1, // 后端API可能从0开始计数
      size: size,
    };

    // 如果有状态过滤，添加到参数中
    if (status) {
      params.status = status;
    }

    const res = await listFoods(merchantStore.currentStoreId, params);
    console.log("获取商品列表响应:", res);

    // 详细分析响应数据结构
    if (res.data) {
      console.log("响应数据:", res.data);
      console.log("数据类型:", typeof res.data);

      if (res.data.data) {
        console.log("res.data.data存在:", res.data.data);
      } else {
        console.log("res.data.data不存在，直接使用res.data");
      }
    } else {
      console.log("响应中没有data字段");
    }

    const list = res.data?.data || res.data;
    console.log("提取的列表数据:", list);

    if (Array.isArray(list)) {
      console.log("列表是数组，长度:", list.length);
      products.value = list;
      // 无法获取总数，假设总数就是当前页的数量
      total.value = list.length;
    } else if (list?.list && Array.isArray(list.list)) {
      console.log("列表在list.list中，长度:", list.list.length);
      products.value = list.list;
      // 尝试获取总数
      total.value = list.total || list.totalElements || list.list.length;
    } else if (list?.content && Array.isArray(list.content)) {
      console.log("列表在list.content中，长度:", list.content.length);
      products.value = list.content;
      // 设置分页信息
      total.value = list.totalElements || 0;
      currentPage.value = list.number ? list.number + 1 : page; // 后端可能从0开始计数
      pageSize.value = list.size || size;
    } else {
      console.log("未找到有效的商品列表数据");
      products.value = [];
      total.value = 0;
    }

    console.log("最终设置的商品列表:", products.value);
    console.log(
      "分页信息 - 当前页:",
      currentPage.value,
      "每页数量:",
      pageSize.value,
      "总数:",
      total.value
    );
    console.log("======================================");
    console.log("商品列表获取完成");
    console.log("======================================");
  } catch (error) {
    console.error("获取商品列表失败", error);
    ElMessage.error("获取商品列表失败");
    products.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取分类列表
const fetchCategories = async () => {
  if (!merchantStore.currentStoreId) {
    categories.value = [];
    return;
  }
  try {
    // 从店铺详情API获取商品分类
    const { getCategories } = await import("@/api/merchant");

    console.log("获取店铺特定商品分类");
    const categoriesData = await getCategories(merchantStore.currentStoreId);

    console.log("获取店铺分类响应:", categoriesData);

    // 设置商品分类数据
    categories.value = categoriesData || [];

    console.log("店铺分类数据:", categories.value);
  } catch (error) {
    console.error("获取分类列表失败", error);
    categories.value = [];
  }
};

const openAddProduct = () => {
  isEdit.value = false;
  productForm.value = {
    name: "",
    categoryId: "",
    price: 0,
    originalPrice: 0,
    inventory: 0,
    description: "",
    image: "",
    status: 1,
  };
  productDialogVisible.value = true;
};

const openEditProduct = (row: any) => {
  isEdit.value = true;
  console.log("编辑商品，原始数据:", row);

  productForm.value = {
    id: row.id,
    name: row.name,
    categoryId: row.categoryId,
    price: row.price,
    originalPrice: row.originalPrice || row.price,
    inventory: row.inventory || row.stock,
    description: row.description || "",
    image: row.image || "",
    status: row.status === "ON_SHELF" ? 1 : 0,
  };

  console.log("编辑商品，表单数据:", productForm.value);
  productDialogVisible.value = true;
};

const handleSaveProduct = async (formData: any) => {
  formLoading.value = true;
  try {
    console.log("准备保存商品数据:", formData);
    console.log("当前店铺ID:", merchantStore.currentStoreId);

    if (isEdit.value) {
      console.log("更新商品，ID:", formData.id);
      const response = await updateFood(
        merchantStore.currentStoreId,
        formData.id,
        formData
      );
      console.log("更新商品响应:", response);
      // ElMessage.success("商品信息已更新，需要管理员审核后才会生效");

      // // 切换到待审核状态过滤
      // statusFilter.value = "PENDING";
    } else {
      console.log("创建新商品");
      const response = await createFood(merchantStore.currentStoreId, formData);
      console.log("创建商品响应:", response);

      // 使用MessageBox显示更详细的成功信息
      ElMessageBox.alert(
        // "商品已创建成功，但需要管理员审核通过后才会显示为上架状态。现在将为您显示待审核的商品列表。",
        "商品创建成功",
        {
          confirmButtonText: "确定",
          type: "success",
        }
      );

      // 切换到待审核状态过滤
      // statusFilter.value = "PENDING";
    }

    productDialogVisible.value = false;
    // 获取待审核状态的商品列表
    await fetchProducts(1, pageSize.value, statusFilter.value);
  } catch (error) {
    console.error("保存商品失败:", error);
    ElMessage.error("操作失败，请检查网络连接或联系管理员");
  } finally {
    formLoading.value = false;
  }
};

const handleCancelForm = () => {
  productDialogVisible.value = false;
};

const handleDeleteProduct = async (row: any) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "提示", {
      type: "warning",
    });
    await deleteFood(merchantStore.currentStoreId, row.id);
    ElMessage.success("商品已删除");
    await fetchProducts();
  } catch {}
};

// 根据分类ID获取分类名称
const getCategoryName = (categoryId: string | number) => {
  if (!categoryId) return "未分类";

  // 尝试将categoryId转换为数字和字符串两种形式进行比较
  const numericCategoryId =
    typeof categoryId === "string" ? parseInt(categoryId) : categoryId;
  const stringCategoryId = categoryId.toString();

  const category = categories.value.find(
    (cat) =>
      cat.id === categoryId ||
      cat.id === numericCategoryId ||
      cat.id.toString() === stringCategoryId
  );

  return category ? category.name : "未知分类";
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  fetchProducts(page, pageSize.value);
};

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchProducts(currentPage.value, size);
};

// 处理状态过滤变化
const handleStatusChange = (status: string) => {
  statusFilter.value = status;
  fetchProducts(1, pageSize.value, status);
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取商品列表和分类列表
  await fetchProducts();
  await fetchCategories();
});

// 监听店铺变化
watch(
  () => merchantStore.currentStoreId,
  async () => {
    await fetchProducts();
    await fetchCategories();
  }
);
</script>

<template>
  <merchant-layout>
    <div class="products-view">
      <el-card class="products-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>商品管理</span>
            <div class="header-buttons">
              <el-button
                type="primary"
                size="small"
                @click="fetchProducts()"
                :loading="loading"
                :disabled="!merchantStore.currentStoreId"
              >
                刷新列表
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="openAddProduct"
                :disabled="!merchantStore.currentStoreId"
              >
                新增商品
              </el-button>
            </div>
          </div>
        </template>

        <!-- 添加状态过滤器 -->
        <div class="filter-container" v-if="merchantStore.currentStoreId">
          <span class="filter-label">状态过滤:</span>
          <el-radio-group
            v-model="statusFilter"
            @change="handleStatusChange"
            size="small"
          >
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="ON_SHELF">上架</el-radio-button>
            <el-radio-button label="OFF_SHELF">下架</el-radio-button>
            <el-radio-button label="PENDING">待审核</el-radio-button>
            <el-radio-button label="SUSPENDED">已禁用</el-radio-button>
          </el-radio-group>
        </div>

        <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
          <el-empty description="请先选择店铺" />
        </div>

        <el-table
          v-else
          :data="products"
          v-loading="loading"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="name" label="商品名称" />
          <el-table-column label="商品图片" width="100">
            <template #default="scope">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                style="
                  width: 50px;
                  height: 50px;
                  object-fit: cover;
                  border-radius: 4px;
                "
                :preview-src-list="[scope.row.image]"
              />
              <div
                v-else
                style="
                  width: 50px;
                  height: 50px;
                  background: #f5f7fa;
                  border-radius: 4px;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类">
            <template #default="scope">
              {{ getCategoryName(scope.row.categoryId) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格">
            <template #default="scope">¥{{ scope.row.price }}</template>
          </el-table-column>
          <el-table-column prop="inventory" label="库存">
            <template #default="scope">{{
              scope.row.inventory || scope.row.stock || 0
            }}</template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="getStatusInfo(scope.row.status).type">
                {{ getStatusInfo(scope.row.status).text }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button size="small" @click="openEditProduct(scope.row)">
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteProduct(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>

      <el-dialog
        v-model="productDialogVisible"
        width="650px"
        :show-close="false"
        :destroy-on-close="true"
      >
        <template #header>
          <div class="custom-dialog-header">
            <span>{{ isEdit ? "编辑商品" : "新增商品" }}</span>
            <button
              class="custom-close-btn"
              @click="productDialogVisible = false"
              aria-label="关闭"
            >
              <el-icon><Close /></el-icon>
            </button>
          </div>
        </template>

        <ProductForm
          :product="productForm"
          :categories="categories"
          :loading="formLoading"
          @submit="handleSaveProduct"
          @cancel="handleCancelForm"
        />
      </el-dialog>
    </div>
  </merchant-layout>
</template>

<style scoped>
.products-view {
  min-height: 100vh;
  background-color: var(--bg-main);
}

.el-header {
  background-color: var(--bg-default);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: var(--text-secondary);
}

.el-main {
  padding: 20px;
}

.products-card {
  border-radius: 18px;
  background: var(--bg-default);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
}

.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  padding-right: 4px;
}
.custom-close-btn {
  border: none;
  background: #f5f6fa;
  border-radius: 50%;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-left: 8px;
}
.custom-close-btn:hover {
  background: #ffd54f;
  color: #a05a1c;
  box-shadow: 0 4px 16px rgba(255, 213, 79, 0.15);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: 500;
}
</style>
